//
//  SY_SchoolFormViewController.m
//  FaceRecognition
//
//  Created by syun on 2017/10/26.
//  Copyright © 2017年 Sylar. All rights reserved.
//

#import "SY_SchoolFormViewController.h"
#import "SY_ClassFormCustomCell.h"
#import "DateView.h"
#import "PNChart.h"
#import "SY_FormModel.h"
@interface SY_SchoolFormViewController ()<UITableViewDelegate,UITableViewDataSource,UIPickerViewDataSource,UIPickerViewDataSource,ArrowViewDelegate,reloadDataDelegate>
{
    DateView *dateV;
    BOOL isOpen;
    NSString * todayData;
    NSString * sarrivalcount0;//旷课
    NSString * sarrivalcount1;//正常
    NSString * sarrivalcount2;//迟到
    NSString * sarrivalcount3;//请假
    NSInteger pageNum;
    NSDate * currentDate;
    
    NSString * todayStr;
    
    EmptyStateView *noWifiView;//无网络状态

}
@property (nonatomic, strong)UITableView *table;
@property (nonatomic, strong)UIDatePicker *pickerView;
@property (nonatomic, strong)UIControl *backControl;
@property (nonatomic, strong)UIButton * dataButton;
@property (nonatomic,strong) PNPieChart *chartView;
@property (nonatomic, strong)NSMutableArray * dataArray;
@property (nonatomic ,strong) UILabel * emptyLabel;
@end

@implementation SY_SchoolFormViewController

#pragma initView

- (UITableView *)table
{
    if (_table == nil) {
        
        _table = [[UITableView alloc]initWithFrame:CGRectMake(0, SafeAreaTopHeight, SCREENWIDTH, SCREENHEIGH - SafeAreaTopHeight - SafeAreaBottomHeight) style:UITableViewStylePlain];
        _table.delegate = self;
        _table.dataSource = self;
        _table.showsVerticalScrollIndicator = NO;
        _table.separatorStyle = UITableViewCellSeparatorStyleNone;
        _emptyLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 284 +(SCREENHEIGH - 348)/2, VIEW_WIDTH, 15)];
        _emptyLabel.font = [UIFont systemFontOfSize:15];
        _emptyLabel.text = @"暂无数据";
        _emptyLabel.textColor = [UIColor colorWithHexString:@"#979797"];
        _emptyLabel.textAlignment = NSTextAlignmentCenter;
        _emptyLabel.hidden = YES;
        [_table addSubview:_emptyLabel];
    }
    
    return _table;
    
}

- (NSMutableArray *)dataArray
{
    if (_dataArray == nil) {
        
        _dataArray = [[NSMutableArray alloc]init];
    }
    
    return _dataArray;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.navBar.nav_titleLabel.text = @"全体宝宝";
    
    NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
    currentDate = [NSDate dateWithTimeIntervalSince1970:time];
    
    sarrivalcount0 = @"0";
    sarrivalcount1 = @"0";
    sarrivalcount2 = @"0";
    sarrivalcount3 = @"0";
    
    todayData = [self getCurrentTime];
    todayStr = todayData;
    
    [self requestAllStudentData];
    [self requestAllStudentList];
    [self.view addSubview:self.table];
    
    noWifiView = [[EmptyStateView alloc] initNoWifiWithFrame:CGRectMake(0, (SCREENHEIGH-64-175)/2, SCREENWIDTH, 175) andBackImage:@"noWifi" andBottomStr:@"网络出错啦,点击重新加载"];
    noWifiView.userInteractionEnabled= YES;
    noWifiView.delegate = self;
    [self.view addSubview:noWifiView];

    
    // Do any additional setup after loading the view.
}

- (void)reloadCurrentData
{
    self.table.hidden = NO;
    [noWifiView hideEmptyImage];
    [self requestAllStudentData];
    [self requestAllStudentList];
}

#pragma UItableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        
        return 2;
    }else{
        
        return self.dataArray.count+1;
        
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 12;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView * view =[[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 12)];
    view.backgroundColor = [UIColor colorWithHexString:@"f4f5f7"];
    return view;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        
        if (indexPath.row == 0) {
            
            return 40;
        }else
        {
            return 184;
        }
    }else
    {
        if (indexPath.row == 0) {
            
            return 40;
            
        }else
        {
            return 39;
        }
    }
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        
        if (indexPath.row == 0) {
            
            UITableViewCell * cell =[tableView dequeueReusableCellWithIdentifier:@"cell"];
            if (cell == nil) {
                
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
                UILabel * markLabel = [[UILabel alloc]initWithFrame:CGRectMake(12, 12, 150, 15)];
                markLabel.text = @"全校宝宝出勤";
                markLabel.font = [UIFont systemFontOfSize:16];
                markLabel.textColor = [UIColor colorWithHexString:@"000000"];
                [cell.contentView addSubview:markLabel];
                
                _dataButton = [UIButton buttonWithType:UIButtonTypeCustom];
                _dataButton.frame = CGRectMake(SCREENWIDTH-12-150, 0, 150, 44);
                [_dataButton setTitleColor:[UIColor colorWithHexString:@"979797"] forState:UIControlStateNormal];
                [_dataButton addTarget:self action:@selector(chooseDataAction:) forControlEvents:UIControlEventTouchUpInside];
                [_dataButton setImageEdgeInsets:UIEdgeInsetsMake(0, 138, 0, 0)];
                [_dataButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 20)];
                _dataButton.titleLabel.font = [UIFont systemFontOfSize:14];
                [_dataButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
                
                if ([todayStr isEqualToString:todayData]) {
                    
                    [_dataButton setTitle:[NSString stringWithFormat:@"今日(%@)",todayStr] forState:UIControlStateNormal];
                    
                }else
                {
                    [_dataButton setTitle:todayData forState:UIControlStateNormal];
                }
                
                [_dataButton setImage:[UIImage imageNamed:@"record_head_classchoose_down_"] forState:UIControlStateNormal];
                [cell.contentView addSubview:_dataButton];
                
                UIView * line = [[UIView alloc]initWithFrame:CGRectMake(12, 39.5, SCREENWIDTH-12, 0.5)];
                line.backgroundColor = [UIColor colorWithHexString:@"dedede"];
                [cell.contentView addSubview:line];
            }

            return cell;
        }else
        {
            UITableViewCell * cell =[tableView dequeueReusableCellWithIdentifier:@"cell"];
            if (cell == nil) {
                
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            for (UIView *view in cell.contentView.subviews) {
                
                
                [view removeFromSuperview];
                
            }
            
            NSMutableArray *arrM = [NSMutableArray array];
            
            NSArray * numArr = @[sarrivalcount2,sarrivalcount0,sarrivalcount3,sarrivalcount1];
            NSArray * colorArr = @[@"e8b8f9",@"b786ca",@"ffb7cf",@"ffd6b3"];
            
            NSString * txt2 = [NSString stringWithFormat:@"迟到 %@",sarrivalcount2];
            NSString * txt0 = [NSString stringWithFormat:@"旷课 %@",sarrivalcount0];
            NSString * txt3 = [NSString stringWithFormat:@"请假 %@",sarrivalcount3];
            NSString * txt1 = [NSString stringWithFormat:@"正常 %@",sarrivalcount1];
            
            NSArray * txtArr = @[txt2,txt0,txt3,txt1];
            
            NSLog(@"%@  %@  %@ ",numArr,colorArr,txtArr);
            
            for (int i = 0; i<4; i++) {
                
                NSString * colorStr = [NSString stringWithFormat:@"%@",[colorArr objectAtIndex:i]];
                
                PNPieChartDataItem *item =  [PNPieChartDataItem dataItemWithValue:[[numArr objectAtIndex:i] integerValue] color:[UIColor colorWithHexString:colorStr] description:[txtArr objectAtIndex:i]];
                
                [arrM addObject:item];
            }
            
            NSLog(@"%@",arrM);
            
            _chartView = [[PNPieChart alloc] initWithFrame:CGRectMake(30, 15, 140, 140) items:arrM];
            _chartView.descriptionTextFont  = [UIFont fontWithName:@"Avenir-Medium" size:11.0];
            _chartView.descriptionTextShadowColor = [UIColor clearColor];
            _chartView.showAbsoluteValues = NO;
            _chartView.showOnlyValues = YES;
            
            [_chartView strokeChart];
            
            
            _chartView.legendStyle = PNLegendItemStyleStacked;
            _chartView.legendFont = [UIFont systemFontOfSize:15];
            
            UIView *legend = [_chartView getLegendWithMaxWidth:200];
            [legend setFrame:CGRectMake(230, 64, legend.frame.size.width, legend.frame.size.height)];
            [cell.contentView addSubview:legend];
            
            [cell.contentView addSubview:_chartView];
            
            return cell;
        }
        
    }else
    {
        if (indexPath.row == 0) {
            
            UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell2"];
            if (cell == nil) {
                
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell2"];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                UILabel * markLabel = [[UILabel alloc]initWithFrame:CGRectMake(12, 12, 150, 15)];
                markLabel.text = @"全校宝宝月统计详情";
                markLabel.textColor = [UIColor colorWithHexString:@"000000"];
                markLabel.font = [UIFont systemFontOfSize:16];
                [cell.contentView addSubview:markLabel];
                
                UIView * line = [[UIView alloc]initWithFrame:CGRectMake(12, 39.5, SCREENWIDTH-12, 0.5)];
                line.backgroundColor = [UIColor colorWithHexString:@"dedede"];
                [cell.contentView addSubview:line];
            }

            return cell;
            
        }else
        {
             SY_FormModel * model = [self.dataArray objectAtIndex:indexPath.row-1];
            
            SY_ClassFormCustomCell * cell = [tableView dequeueReusableCellWithIdentifier:@"SY_ClassFormCustomCell"];
            if (cell == nil) {
                
                cell = [[SY_ClassFormCustomCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"SY_ClassFormCustomCell"];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.timeLable.text = model.date;
            cell.lateNum.text = [NSString stringWithFormat:@"%@迟到",model.sarrivalcount2];
            cell.absentNum.text = [NSString stringWithFormat:@"%@旷课",model.sarrivalcount0];
            cell.leaveNum.text = [NSString stringWithFormat:@"%@请假",model.sarrivalcount3];
            return cell;
        }
        
    }
    
    
}

- (void)chooseDataAction:(UIButton *)sender
{
    isOpen = !isOpen;
    
    if (isOpen == YES) {
        [_dataButton setImage:[UIImage imageNamed:@"record_head_classchoose_up_"] forState:UIControlStateNormal];
    }
    
    dateV = [[DateView alloc] initAddSuperView:self.view canceltype:1];
    
    __weak SY_SchoolFormViewController * weakself = self;
    dateV.aDelegate = weakself;
    dateV.datePicker.maximumDate = currentDate;
    
    dateV.getDate = ^(NSString *dateStr){
        NSMutableString * dateS = [NSMutableString stringWithFormat:@"%@",dateStr];
        NSString * date = [[dateS componentsSeparatedByString:@" "] firstObject];

        todayData = date;
        if ([todayStr isEqualToString:todayData]) {
            
            [weakself.dataButton setTitle:[NSString stringWithFormat:@"今日(%@)",todayStr] forState:UIControlStateNormal];
            
        }else
        {
            [weakself.dataButton setTitle:todayData forState:UIControlStateNormal];
        }
        
        [weakself requestAllStudentData];
        [weakself requestAllStudentList];
    };
    
}

- (void)changeArrowDirection:(BOOL)Flag
{
    if (Flag == YES) {
        
        [_dataButton setImage:[UIImage imageNamed:@"record_head_classchoose_down_"] forState:UIControlStateNormal];
    }
}

- (NSString *)getCurrentTime {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *dateTime = [formatter stringFromDate:[NSDate date]];
    return dateTime;
}

- (void)requestAllStudentData
{
    NSMutableDictionary *requestDic = [NSMutableDictionary dictionary];
    
    NSString * scid = [SYAccountTool ShareAccount].account.scid;
    [requestDic setObject:scid forKey:@"scid"];
    [requestDic setObject:todayData forKey:@"date"];
    [Utils Java_get:@"api/getSchoolStudentTotle" parameters:requestDic success:^(NSInteger recode, id jsonObject) {
        
        NSArray *arr = [jsonObject objectForKey:@"re_data"];
        if (arr.count > 0) {
            
            NSDictionary *dic = [arr objectAtIndex:0];
            sarrivalcount0 = [dic objectForKey:@"sarrivalcount0"];
            sarrivalcount1 = [dic objectForKey:@"sarrivalcount1"];
            sarrivalcount2 = [dic objectForKey:@"sarrivalcount2"];
            sarrivalcount3 = [dic objectForKey:@"sarrivalcount3"];
            
        }else
        {
            sarrivalcount0 = @"0";
            sarrivalcount1 = @"0";
            sarrivalcount2 = @"0";
            sarrivalcount3 = @"0";
        }
        
        [self.table reloadData];
        
    }failure:^(NSInteger recode, NSError *error) {
        
        if (error.code == -1009) {
            self.table.hidden = YES;
            [self->noWifiView showEmptyImage];
        }
        
    }];
}

- (void)requestAllStudentList
{
    
    NSMutableDictionary *requestDic = [NSMutableDictionary dictionary];
    
    NSString * scid = [SYAccountTool ShareAccount].account.scid;
    [requestDic setObject:scid forKey:@"scid"];
    [requestDic setObject:todayData forKey:@"date"];
    [Utils Java_get:@"api/getSchoolStudentTotleList" parameters:requestDic success:^(NSInteger recode, id jsonObject) {
        
        [self.dataArray removeAllObjects];
        
        NSArray *arr = [jsonObject objectForKey:@"re_data"];
        
        NSLog(@"arr = %@",arr);
        if ([arr isKindOfClass:[NSNull class]] || ![arr isKindOfClass:[NSArray class]] || arr.count == 0) {
            
            [_emptyLabel setHidden:NO];
            [self.table reloadData];
            return;
            
        }else
        {
            [_emptyLabel setHidden:YES];
            for ( NSDictionary * dic in arr) {
                
                SY_FormModel * model = [SY_FormModel mj_objectWithKeyValues:dic];
                [self.dataArray addObject:model];
            }
        }
        
        [self.table reloadData];
        
    }failure:^(NSInteger recode, NSError *error) {
        
        if (error.code == -1009) {
            self.table.hidden = YES;
            [self->noWifiView showEmptyImage];
        }
    }];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
